package com.sy.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sy.exception.BusinessException;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SMSCustomerUtils {
    private SMSCustomerUtils() {

    }

    /**
     * 系统给当前对象发送短信
     * @param mobile 向哪个手机号发送
     * @param phone  发送给当前对象的咨询顾客手机号码
     * @param userName 发送给当前对象的咨询顾客名称
     * @return
     */
    public static JSONObject sendValidateCode(String phone, String mobile,String userName) {
        try {
            //创建连接
            URL url = new URL("http://api01.monyun.cn:7901/sms/v2/std/single_send");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            // POST请求
            DataOutputStream out = new
                    DataOutputStream(connection.getOutputStream());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("apikey", "57b46681e3a3f4d82a9087cc05baa3ec");
            jsonObject.put("mobile", mobile);
            jsonObject.put("content", URLEncoder.encode("您手机的注册验证码为："+"123456789"+"，如有问题请拨打客服电话： "+phone, "gbk"));//您手机的注册验证码为：123456789，如有问题请拨打客服电话： 15207964953
            out.writeBytes(jsonObject.toJSONString());
            out.flush();
            out.close();
            // 读取响应
            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                sb.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
            return JSON.parseObject(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("短信发送失败...");
        }
    }

}
